package store.lunangangster.engine.bpmn.parser.handler;

import java.util.Optional;
import store.lunangangster.bpmn.model.BaseElement;
import store.lunangangster.bpmn.model.BoundaryEvent;
import store.lunangangster.bpmn.model.FlowElement;
import store.lunangangster.bpmn.model.Message;
import store.lunangangster.bpmn.model.StartEvent;
import store.lunangangster.bpmn.model.definition.MessageEventDefinition;
import store.lunangangster.engine.bpmn.parser.BpmnParser;
import store.lunangangster.engine.impl.bpmn.behavior.BoundaryMessageEventBehavior;
import store.lunangangster.engine.impl.bpmn.behavior.StartMessageEventBehavior;

public class MessageEventDefinitionParseHandler extends AbstractBpmnParseHandler<MessageEventDefinition> {

  @Override
  public void handle0(BpmnParser bpmnParser, MessageEventDefinition messageEventDefinition) {
    BaseElement element = Optional.ofNullable(
            bpmnParser.getBpmnModel().getElementMap().get(Message.class))
        .map(map -> map.get(messageEventDefinition.getMessageRef())).orElse(null);


    if (element instanceof Message) {
      messageEventDefinition.setMessage((Message) element);
    }

    FlowElement currentElement = bpmnParser.getCurrentElement();
    if (currentElement instanceof BoundaryEvent) {
      BoundaryEvent boundaryEvent = (BoundaryEvent) currentElement;
      boundaryEvent.setBehavior(new BoundaryMessageEventBehavior());
    } else if (currentElement instanceof StartEvent) {
      StartEvent startEvent = (StartEvent) currentElement;
      startEvent.setBehavior(new StartMessageEventBehavior());
    }
  }

  @Override
  public Class<? extends BaseElement> getType() {
    return MessageEventDefinition.class;
  }
}
